<?php
/*
Copyright (C) 2011  Benjamin Marchand

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
class PrivateController extends AppController
{
	var $name = "Private";
	var $view = 'Theme';
	//var $theme  = 'minecraft';
	var $helpers = array('Paginator','Html','Javascript','Session','Js' => array('jquery'));
	var $components = array('RequestHandler','Session','Minelink','Auth','Remotetoolkit','Phptelnet');
	var $uses = array('item','User','Setting','mctemplateplugin'); 
	var $cacheAction = "1 minute";
	var $paginate = array('limit' => 12);
	
	function isAuthorized()
	{
		if ($this->Auth->user('group')==1)
			return TRUE;
		else
			return FALSE; 
	}
	
	function beforeRender()
	{
		if ($this->Auth->user('group')<>1)
		{
			$this->redirect(array('controller'=>'public','action'=>'index'));
		}
		$theme = Configure::read('bukkitadmin.theme');
		if (!empty($theme))
		{
			$this->theme = $theme;
		}
	}
	
	function index()
	{
		$this->layout = "private";
		$this->set('title_for_layout',"Webukkit");
		$config = Configure::read('bukkitadmin');
		if (empty($config))
		{
			$this->set('message',"Warning, you should configure Webukkit!");
			$this->set('url','view_config');
		}
	}
	
	function beforeFilter(){
		//reads the site-wide config values from the DB and puts them through the Configure::write method
		parent::beforeFilter();
		$this->Setting->getcfg();
		$this->set('version',Configure::read('version'));
	}
	
	function afterFilter(){
		//retrieves the site-wide configurations from Configure::read($key) and puts it back into the db if new
		$this->Setting->writecfg();
		} 
	
		function refresh_player_panel()
	{
		$this->autoLayout = false;
		if ($this->Minelink->createSocket())
		{
			$this->set('players',$this->Minelink->players());
		}
		$this->set('listitems',$this->item->find('all',array('order'=>'name')));
		$this->render('/elements/playerpanel');
	}
	
	function view_status()
	{
		$this->autoLayout = false;
		if (Configure::read('bukkitadmin.useTcpBukkit'))
		{
			if ($this->Minelink->createSocket())
			{
				$this->__get_minelink_status();
			}
			};
		if (Configure::read('bukkitadmin.useRemoteToolkit'))
		{
			$this->set('RemoteToolkitRunning',$this->Remotetoolkit->createSocket());
			};
		$this->set('listitems',$this->item->find('all',array('order'=>'name')));
		$this->set('useRemoteToolkit',Configure::read('bukkitadmin.useRemoteToolkit'));
		$this->set('useTcpBukkit',Configure::read('bukkitadmin.useTcpBukkit'));
	}
	
	// Command sent by the view_status windows
	function sendremotecommand()
	{
		$this->autoLayout = false;
		$this->autoRender = false;
		if ($this->Remotetoolkit->createSocket())
		{
			echo $this->Remotetoolkit->cmd($this->params['form']['command']);
		}
	}
	
	function __get_minelink_status()
	{
		$this->set('serverstatus',$this->Minelink->server_status());
		$this->set('pid',$this->Minelink->pid());
		$this->set('cpu_usage',$this->Minelink->cpu_usage());
		$this->set('mem_usage',$this->Minelink->mem_usage());
		$this->set('players',$this->Minelink->players());
	}
	
	function kick_player()
	{
		$this->autoLayout = false;
		$this->autoRender = false;
		if ($this->Minelink->createSocket())
		{
			$this->Minelink->kick_player($this->params['form']['player']);
		}
		$this->set('players',$this->Minelink->players());
		$this->render('/elements/playerpanel');
	}
	
	function pm_player()
	{
		$this->autoLayout = false;
		$this->autoRender = false;
		$this->Minelink->createSocket();
		$this->Minelink->pm_player($this->params['form']['player'],$this->params['form']['msg']);
	}
	
	// Set the visibility of plugins in the permissions of webukkit
	function _setpluginwebukkitperm()
	{
		$this->set('statsplugin',$this->_pluginexist('Stats'));
		$this->set('achplugin',$this->_pluginexist('Achievements'));
	}

	function view_config()
	{
		$this->autoLayout = FALSE;
		$this->Setting->getcfg();
		$this->set('websitename',Configure::read('bukkitadmin.websitename'));
		$this->set('defaulttheme',Configure::read('bukkitadmin.theme'));
		$this->set('themes',$this->_getthemeslist());
		$this->set('items',$this->paginate('item'));
		$this->set('users',$this->paginate('User'));
		$minecraftpath = Configure::read('bukkitadmin.MinecraftPath');
		$this->set('dynmap',Configure::read('bukkitadmin.dynmap'));
		$this->set('useTcpBukkit',Configure::read('bukkitadmin.useTcpBukkit'));
		$this->set('MinecraftPath',$minecraftpath);
		$this->set('useRemoteToolkit',Configure::read('bukkitadmin.useRemoteToolkit'));
		$this->set('usePermissionsPlugin',Configure::read('bukkitadmin.usePermissionsPlugin'));
		$this->set('ppdefaultgroup',Configure::read('bukkitadmin.ppdefaultgroup'));
		$this->set('ppdefaultworld',Configure::read('bukkitadmin.ppdefaultworld'));
		$this->set('mapsystem',Configure::read('bukkitadmin.Mapsystem'));
		$this->data['config'] = Configure::read('bukkitadmin');
		
		$this->_setpluginwebukkitperm();
		// stats
		$this->data['sitepermissions']['statspublicview'] = Configure::read('bukkitadmin.statspublicview');
		$this->data['sitepermissions']['statsregisteredview'] = Configure::read('bukkitadmin.statsregisteredview');		
		// map
		$this->data['sitepermissions']['mappublicview'] = Configure::read('bukkitadmin.mappublicview');
		$this->data['sitepermissions']['mapregisteredview'] = Configure::read('bukkitadmin.mapregisteredview');
		// achievements
		$this->data['sitepermissions']['achpublicview'] = Configure::read('bukkitadmin.achpublicview');
		$this->data['sitepermissions']['achregisteredview'] = Configure::read('bukkitadmin.achregisteredview');

		$defaultworld = Configure::read('bukkitadmin.ppdefaultworld');
		$path = APP.'tmp'.DS;
		// We check is the minecraft path exist
		if (file_exists($minecraftpath))
		{
			$groups = json_decode($this->requestAction(array('controller'=>'plugins','action'=>'getPPGroups'),array('form'=>array('world'=>$defaultworld))),true);
			// if minecraft path exist, we can check Permissions plugin
			$this->set('ppgroups',$groups);
			$this->set('ppworlds',$this->requestAction(array('controller'=>'plugins','action'=>'showpermworlds')));
			// We check is the minecraft path is writable
			if (is_writable($minecraftpath) && ($this->is_removeable($minecraftpath.'plugins'.DS)))
			{
				$mcpathmessage = '<img src="'.$this->webroot.IMAGES_URL.'/check-success.png" style="vertical-align:middle;padding-right:10px;">The Minecraft directory and subdirectories are writable, correct!<br/>';
			}
			else
			{
				$mcpathmessage = '<img src="'.$this->webroot.IMAGES_URL.'/clear_icon.png" style="vertical-align:middle;padding-right:10px;">Error ! The Minecraft directory and subdirectory "plugins" must be writable!';
			}
		}
		else
		{
			$mcpathmessage = '<img src="'.$this->webroot.IMAGES_URL.'/clear_icon.png" style="vertical-align:middle;padding-right:10px;">Error ! Minecraft path don\'t exist!';
		}
		$this->set('mcpathmessage',$mcpathmessage);
	}
	
	function _getthemeslist()
	{
		$themes['default']='default';
		foreach (glob(ROOT.DS."theme".DS."*",GLOB_ONLYDIR) as $filename) {
			$themes[basename($filename)] = basename($filename);
		}
		return $themes;
	}
	
	function is_removeable($dir)
	{
		$folder = opendir($dir);
		while($file = readdir( $folder ))
			if($file != '.' && $file != '..' && !strpos($file, '.ini',1) && !strpos($file, '.jar',1) &&
		(!is_writable($dir."/".$file) ||
		(is_dir($dir."/".$file) && !$this->is_removeable($dir."/".$file))))
		{
			closedir($dir);
			return false;
		}
		if (!is_string($dir)) closedir($dir);
		return true;
	}
	function save_config()
	{
		$this->autoRender = false;
		$this->autoLayout = false;
		
		$path = $this->data['config']['MinecraftPath'];
		if(substr($path, -1) != DIRECTORY_SEPARATOR) $path .= DIRECTORY_SEPARATOR;
		if (!empty($this->data['config']['theme']) || ($this->data['config']['theme']!='Default'))
			Configure::write('bukkitadmin.theme',$this->data['config']['theme']);
		else
			Configure::write('bukkitadmin.theme','');
		Configure::write('bukkitadmin.websitename',$this->data['config']['websitename']);
		Configure::write('bukkitadmin.useTcpBukkit',$this->data['config']['useTcpBukkit']);
		Configure::write('bukkitadmin.useRemoteToolkit',$this->data['config']['useRemoteToolkit']);
		Configure::write('bukkitadmin.usePermissionsPlugin',$this->data['config']['usePermissionsPlugin']);
		//Configure::write('bukkitadmin.dynmap',$this->data['config']['dynmap']);
		if (!empty($this->data['config']['useTcpBukkit']))
		{
			Configure::write('bukkitadmin.TcpBukkitPassword',$this->data['config']['TcpBukkitPassword']);
			Configure::write('bukkitadmin.TcpBukkitServer',$this->data['config']['TcpBukkitServer']);
			Configure::write('bukkitadmin.TcpBukkitPort',$this->data['config']['TcpBukkitPort']);
		}
		if (!empty($this->data['config']['useRemoteToolkit']))
		{
			Configure::write('bukkitadmin.RemoteToolkitServer',$this->data['config']['RemoteToolkitServer']);
			Configure::write('bukkitadmin.RemoteToolkitPort',$this->data['config']['RemoteToolkitPort']);
			Configure::write('bukkitadmin.RemoteToolkitPassword',$this->data['config']['RemoteToolkitPassword']);
			Configure::write('bukkitadmin.RemoteToolkitUser',$this->data['config']['RemoteToolkitUser']);
		}
		if (!empty($this->data['config']['usePermissionsPlugin']))
		{
			Configure::write('bukkitadmin.ppdefaultgroup',$this->data['config']['ppdefaultgroup']);
			Configure::write('bukkitadmin.ppdefaultworld',$this->data['config']['ppdefaultworld']);
		}
		Configure::write('bukkitadmin.MinecraftPath',$path);
		Configure::write('bukkitadmin.Mapsystem',$this->data['config']['Mapsystem']);
		Configure::write('bukkitadmin.Mapsystemparam',$this->data['config']['Mapsystemparam']);
		
		$this->Setting->writecfg();
		$this->view_config();
		$this->render('view_config');
	}
	
	function saveplugintemplate()
	{
		$this->autoLayout = FALSE;
		$this->autoRender = false;
		$this->mctemplateplugin->save($this->data);
		$this->render('/elements/tableplugin');
	}
	
	function getplugintemplates()
	{
		if (isset($this->params['requested'])) {
			return $this->mctemplateplugin->find('all');
			} else {
			$this->set('plugins',$this->mctemplateplugin->find('all'));
		}
	}
	
	function invadd()
	{
		$this->autoLayout = FALSE;
		$player = $this->params['form']['player'];
		$block_type = $this->params['form']['block_type'];
		$amount = $this->params['form']['amount'];
		if (!empty($player) && !empty($block_type) && !empty($amount) && $this->Minelink->createSocket())
		{
			$this->Minelink->invadd($player,$block_type,$amount);
		}
		$this->show_inv();
	}
	
	public function invremove()
	{
		//$player,$slot,$block_type,$amount
		$this->autoLayout = FALSE;
		$player = $this->params['form']['player'];
		$slot = $this->params['form']['num'];
		if (!empty($player) && $this->Minelink->createSocket())
		{
			$this->Minelink->invremove($player,$slot);
		}
		$this->show_inv();
	}
	
	function show_inv()
	{
		$this->autoRender = false;
		$this->autoLayout = false;
		
		if ($this->Minelink->createSocket())
		{
			$items = $this->Minelink->get_inventory($this->params['form']['player']);
			$this->set('items',$items);
		}
		$datas = $this->item->find('all');
		foreach($datas as $data)
		{
			$images[$data['item']['id']]=array('name'=>$data['item']['name'],'image'=>$data['item']['image']);
		}
		$this->set('images',$images);
		$this->set('playername',$this->params['form']['player']);
		$this->render('/elements/show_inv');
	}
	
	function getitems()
	{
		$this->autoRender = false;
		$this->autoLayout = false;
		$this->paginate = array(
		'order' => array('item.id'),
		'limit' => 12
		);
		if (isset($this->params['requested'])) {
			return $this->paginate('item');
			} else {
			$this->set('items',$this->paginate('item'));
		}
		$this->render('/elements/items');
	}
	
	function delplugintemplate($id=null)
	{
		$this->autoRender = false;
		$this->autoLayout = false;
		
		if (!empty($id))
		{
			$this->mctemplateplugin->delete($id);
		}
		$this->render('/elements/tableplugin');
	}
	
	function changeadminpassword()
	{
		$this->autoRender = false;
		$this->autoLayout = false;
		
		if ($this->data['User']['newpassword']==$this->data['User']['confirmpassword'])
		{
			$data = $this->User->findByUsername('admin');
			$this->data['User']['id'] = $data['User']['id'];
			$this->data['User']['username'] = 'admin';
			if ($this->Auth->password($this->data['User']['oldpassword'])==$data['User']['password'])
			{
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['newpassword']);
				if ($this->User->save($this->data))
				{
					$this->Session->setFlash('Password changed!','flash_success');
				}
				else
				{
					$this->Session->setFlash('Error in password change!','flash_failure');
				}
			}
			else
			{
				$this->Session->setFlash('Old password don\'t match!','flash_failure');
			}
		}
		else
		{
			$this->Session->setFlash('Password don\'t match!','flash_failure');
		}
		$this->data = NULL;
		$this->render('/elements/PasswordTab');
	}
	
	function deluser($id)
	{
		$this->autoRender = false;
		$this->autoLayout = false;
		if (!empty($id) && ($id<>1))
		{
			$this->User->delete($id);
		}
		$this->set('users',$this->paginate('User'));
		$this->render('/elements/config_users');
	}
	
	function view_log()
	{
		// if the minecraft path is defined
		// get the log
		$minecraftpath = Configure::read('bukkitadmin.MinecraftPath');
		if (!empty($minecraftpath))
		{
			//$output = explode("\n", $this->readLastLines($minecraftpath.DS.'server.log',20));
			//$this->Session->write('logpos',0);
			$this->set('config',array_reverse($this->readLastLines($minecraftpath.'server.log',100)));
		}
		else
			echo "Minecraft path is empty!";
	}
	
	function update_log()
	{
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$minecraftpath = Configure::read('bukkitadmin.MinecraftPath');
		if (!empty($minecraftpath))
		{
			//$output = explode("\n", $this->readLastLines($minecraftpath.DS.'server.log',20));
			$this->set('config',array_reverse($this->readLastLines($minecraftpath.'server.log',100)));
		}
		$this->render('/elements/logwindows');
	}
	/*
	Get from http://mydebian.blogdns.org/?p=197
	read last X lines of a given text file
	$filename = full path + filename (i.e. /home/marco/file.txt)
		$lines       = number of lines (i.e. 10)
		*/
	function readLastLines($filename,$lines) {
        $handle = @fopen($filename,"r");
        if (!$handle) {
                echo "Error: can't find or open $filename<br/>\n";
                return -1;
        }

        /*put the whole file in an array */
        $content = explode("\n",file_get_contents($filename));

        fclose($handle);

        $number = count($content);
        $pos = $number -$lines;

        /*if the file contains less lines than we want, then $pos is negative */
        /*We need to translate $pos to zero and ask for less lines at the same time*/
        if ($pos < 0) {
                /* remember that $pos is negative so += here does a subtraction */
                $lines += $pos;

                $pos = 0;
        }
        return array_slice($content,$pos,$lines);

		//$buffer = array_reverse($buffer);
	}
	
	function commandRT()
	{
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$server = Configure::read('bukkitadmin.RemoteToolkitServer');
		$port = Configure::read('bukkitadmin.RemoteToolkitPort');
		$pass = Configure::read('bukkitadmin.RemoteToolkitPassword');
		$user = Configure::read('bukkitadmin.RemoteToolkitUser');
		$result = $this->Phptelnet->Connect($server,$port,$user,$pass);
		switch ($result) {
			case 0:
				$this->Phptelnet->DoCommand($this->data['item']['RTcommandInput'], $display);
				echo $display;
				$this->Phptelnet->Disconnect();
				break;
			case 1:
				echo '[PHP Telnet] Connect failed: Unable to open network connection';
				break;
			case 2:
				echo '[PHP Telnet] Connect failed: Unknown host';
				break;
			case 3:
				echo '[PHP Telnet] Connect failed: Login failed';
				break;
			case 4:
				echo '[PHP Telnet] Connect failed: Your PHP version does not support PHP Telnet';
				break;
			default:
				echo "ah";
				break;
		}
	}
	
	// save permissions for the website
	function savesitepermissions()
	{
		$this->autoLayout=FALSE;
		// map
		Configure::write('bukkitadmin.mappublicview',$this->data['sitepermissions']['mappublicview']);
		Configure::write('bukkitadmin.mapregisteredview',$this->data['sitepermissions']['mapregisteredview']);
		// stats
		Configure::write('bukkitadmin.statspublicview',$this->data['sitepermissions']['statspublicview']);
		Configure::write('bukkitadmin.statsregisteredview',$this->data['sitepermissions']['statsregisteredview']);
		// achievements
		Configure::write('bukkitadmin.achpublicview',$this->data['sitepermissions']['achpublicview']);
		Configure::write('bukkitadmin.achregisteredview',$this->data['sitepermissions']['achregisteredview']);
		$this->_setpluginwebukkitperm();
		$this->render('/elements/config_sitepermissions');
	}
	
	function edituser()
	{
		$this->autoLayout=FALSE;
		$this->autoRender=FALSE;
		if (!empty($this->data['User']['id']))
		{
			$this->User->id=$this->data['User']['id'];
			if (!empty($this->data['User']['password']) && ($this->data['User']['password']==$this->Auth->password($this->data['User']['confirmpassword'])))
			{
				$this->User->save($this->data);
				$this->Session->setFlash('User updated!','flash_success');
			}
			else
			{
				if ($this->User->save($this->data,false,array('id','username','fullname','group','email')))
					$this->Session->setFlash('User updated!','flash_success');
				else
					$this->Session->setFlash('Error in save!','flash_failure');
			}
		}
		$this->set('users',$this->paginate('User'));
		$this->render('/elements/config_users');
	}
	
	function _pluginexist($plugin)
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path .= DS.'plugins'.DS.$plugin.'.jar';
		if (file_exists($path))
			return TRUE;
		else
			return FALSE;
	}
}

?>